package com.emapp.lccode.mode

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.emapp.lccode.base.BaseApplication
import com.emapp.lccode.base.BaseConfig
import com.emapp.lccode.bean.ApiResponse
import com.emapp.lccode.bean.CountHome
import com.emapp.lccode.bean.VersionKt
import com.emapp.lccode.http.apiService
import com.emapp.lccode.utils.BaseUtil
import com.emapp.lccode.utils.XtomLogger
import com.emapp.lccode.utils.toEntity
import com.emapp.lccode.utils.toJsonStr
import com.hjq.toast.Toaster
import com.luck.picture.lib.thread.PictureThreadUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.launch
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import me.hgj.jetpackmvvm.ext.launch
import me.hgj.jetpackmvvm.ext.request
import me.hgj.jetpackmvvm.state.ResultState
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response

class Main2ViewModel : BaseViewModel() {
    var gongdan: MutableLiveData<ResultState<ArrayList<CountHome>>> = MutableLiveData()
    var device: MutableLiveData<ArrayList<CountHome>> = MutableLiveData()
    var test: MutableLiveData<ResultState<Any>> = MutableLiveData()
    var img: MutableLiveData<Bitmap> = MutableLiveData()

    var version: MutableLiveData<VersionKt> = MutableLiveData()
    fun getGongdan() {
        val u = BaseApplication.instance.getUser() ?: return
        request({ apiService.getGongdanCount(u.admin_id) }, gongdan, true)
    }
//    val streamData = flow {
//        val u = BaseApplication.instance.getUser() ?: return@flow
//        val responseBody: ApiResponse<ArrayList<CountHome>> = apiService.getGongdanCount(u.admin_id)
//        emit(responseBody)
////        val reader = BufferedReader(InputStreamReader(responseBody.byteStream()))
////        var line: String?
//
////        while (reader.readLine().also { line = com.amap.api.col.`3sl`.it } != null) {
////            line?.let { emit(it) }
////        }
////
////        reader.close()
//    }.flowOn(Dispatchers.IO)

//    fun collectStreamData(onDataReceived: (ApiResponse<ArrayList<CountHome>>) -> Unit) {
//        viewModelScope.launch {
//            streamData.collect { data ->
//                onDataReceived(data)
//            }
//        }
//    }



    fun getDevice() {
        val u = BaseApplication.instance.getUser() ?: return
        request({ apiService.getDevice(u.admin_id) }, {
            device.value = it
        }, {
            Toaster.show(it.errorMsg)
        })
    }

    fun test() {
        val u = BaseApplication.instance.getUser() ?: return
        request({ apiService.mapAdd(u.admin_id, "", "", "", "", "") }, test, true)
    }

    fun test2() {
        launch({ downloadImage() }, {
            log_e("-------------------------999999")
        })
//        viewModelScope.launch {
//            downloadImage()
//        }
//         GlobalScope.launch(Dispatchers.Main) {
//             delay(1000L) // 延迟1秒
//             finish() // 关闭当前Activity
//         }

    }

    fun downloadImage() {
        // 创建一个GET方式的请求结构
        val request: Request =
            Request.Builder().url(BaseConfig.ROOT_URL + "/api/appapi/addVerify").build()
        OkHttpClient().newCall(request)
            .also {
                it.enqueue(object : Callback {
                    override fun onFailure(call: Call, e: okio.IOException) {
                        PictureThreadUtils.runOnUiThread { log_e("下载网络图片报错：" + e.message) }
                    }

                    override fun onResponse(call: Call, response: Response) {
                        val inputStream = response.body!!.byteStream()
                        // 从返回的输入流中解码获得位图数据
                        val b = BitmapFactory.decodeStream(inputStream)
                        img.postValue(b)
                    }
                })

            }
    }

    fun getVersion() {
        request(
            { apiService.getVersion(BaseUtil.getAppVersionName(BaseApplication.instance)) },
            {
            },
            {
            },
            true
        )
    }

    fun getVersion2(show: Boolean) {
        request({ apiService.getVersion2(BaseUtil.getAppVersionName(BaseApplication.instance)) },
            {
                val intValue: VersionKt? = if (it is Collection<*>) null else it.toJsonStr().toEntity()//it is Collection<*>判断是否为数组【】
                version.postValue(intValue)
            }, {
                if (show)
                    Toaster.show(it.errorMsg)
            }, show
        )
    }

    protected val TAG = this.javaClass.simpleName
    protected open fun log_e(msg: String?) {
        if (BaseConfig.isDebug) XtomLogger.e(TAG, msg)
    }
}